var express = require('express');
var router = express.Router();

const mysql = require('mysql')
// 封装一个创建连接的函数
function getConn() {
  return mysql.createConnection({
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: '123456',
    database: 'my_db'
  })
}
// var connection = mysql.createConnection({
//   host: 'localhost', //数据库地址
//   port: '3306',//端口号
//   user: 'root',//用户名
//   password: '123456',//密码
//   database: 'my_db'//数据库名称
// });


// router.get('/a', function(req, res, next) {
//   res.send('123')
// })


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});
router.post('/demo', function (req, res, next) {
  res.send('get')
  console.log(req.query);
});
router.get('/demo', function (req, res, next) {
  res.send('get')
  console.log(req.query);
});
//一连，二查，三关
router.post('/register', function (req, res, next) {
  const { user, ages, gender, pwd } = req.body
  console.log(req.body);
  // res.send('post请求成功')
  //一连
  const conn = getConn()
  // connection.connect();
  //二查
  //查询语句
  const sql = `INSERT INTO users VALUES (null,'${user}','${ages}','${gender}','${pwd}','2022-10-10 10:00:00')`
  conn.query(sql, (err, data) => {
    if (err) throw err
    console.log(data)
    if (data.affectedRows >= 1) {
      res.send({
        code: 200,
        msg: '注册成功'
      })
    }

  })
  conn.end()
});
//登录接口
router.post('/login', (req,res,next) => {
  const { uname,pwd } = req.body
  console.log(req);
  const conn = getConn()
  sql = `select * from users where uname= '${uname}' and password = '${pwd}'`
  conn.query(sql, (err, data) => {
    if (err) throw err
    // console.log(data);
    if (data.length >= 1) {
      res.send({
        code:200,
        msg:'登录成功',
      })
    }else {
      res.send({
        code:500,
        msg:'用户不存在'
      })
    }
  })
  conn.end()
})
module.exports = router;
